#!/bin/bash

#data_time="2016-12-03 12:00:00"
CUR=`pwd`
data_time=`date -d"3 day ago" +"%Y-%m-%d %H:00:00"`
data_time_now=`date +"%Y-%m-%d %H:00:00"`
version=`date +"%Y%m%d_%H"`
DUMP_DIR=app_data_${version}
#MONGO_ADDR=192.168.1.20:40041
#MONGO_ADDR=120.76.199.10:40041
MONGO_ADDR=172.16.215.16:40042
MONGO_DB=app_data
USERNAME=readme
PASSWORD=readme
MONGO_HOME=/home/dig/deploy/mongodb-linux-x86_64-rhel62-3.2.11
FILE_LOCK=./FILE_LOCK
DUMP_BASE_DIR=/home/dig/graph_data/mongo_data
LAST_DUMP_DATE=./last_dump_data

function try_lock() {
	if [ -f "${FILE_LOCK}" ];then
		echo "file locked"
		exit -1
	fi
	touch ${FILE_LOCK}
}

function unlock() {
	if [ -f "${FILE_LOCK}" ];then
		rm ${FILE_LOCK}
	fi
}
mkdir -p ${DUMP_BASE_DIR}
cd ${DUMP_BASE_DIR}
mkdir -p ${DUMP_DIR}

if [ -f "${LAST_DUMP_DATE}" ];then
    data_time=`cat ${LAST_DUMP_DATE}`
fi

echo ${data_time}  ${data_time_now} ${DUMP_DIR}
#要导出的表名
#COLLECTIONS="enterprise_data_gov bulletin judge_process court_ktgg judgement_wenshu bid_detail top_ten_shareholder enterprise_owing_tax patent penalty shixin_info ssgs_baseinfo tax_payer_level_A annual_reports"
COLLECTIONS="enterprise_data_gov bulletin judge_process court_ktgg patent penalty shixin_info ssgs_notice judgement_wenshu zhixing_info bid_detail top_ten_shareholder annual_reports investment_events land_auction ppp_project land_project_selling land_selling_auction neighborhood_anjuke xiaoqu_lianjia ssgs_caibao_cash_flow ssgs_caibao_companies_ability ssgs_caibao_profit ssgs_caibao_assets_liabilities industry_news net_loan_blacklist baidu_news tax_payer_level_A land_value enterprise_data_gov_change_info ssgs_notice_cninfo enterprise_owing_tax ssgs_baseinfo"

#输出导出区间到版本信息
echo -e "${data_time}\n${data_time_now}" >${DUMP_DIR}/versions
for col in ${COLLECTIONS}
do
    try_cnt=0
    while [ ${try_cnt} -lt 4 ];
    do
        ${MONGO_HOME}/bin/mongodump -h ${MONGO_ADDR} -d ${MONGO_DB} -c ${col} --query="{\"_utime\":{\$gte: \"${data_time}\"}}" --username=${USERNAME} --password=${PASSWORD} --gzip -o ${DUMP_DIR}
        ret=$?
        if [ "$ret" != "0" ];then
            echo "dump $col faied"
        else
            break
        fi
        try_cnt=`expr ${try_cnt} + 1`
        if [ ${try_cnt} -ge 4 ];then
            exit -1
        fi
    done
done
try_lock 
tar -cf ${DUMP_DIR}.tar_taring ${DUMP_DIR}
mv ${DUMP_DIR}.tar_taring ${DUMP_DIR}.tar
rm -rf ${DUMP_DIR}
unlock

#输出上次导出时间
echo "${data_time_now}" > ${LAST_DUMP_DATE}

